package inet.app.vod.adapter;

import inet.app.vod.activity.R;
import inet.app.vod.object.FunModel;

import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.inet.app.framework.bitmap.BitmapUtil;
import com.inet.app.framework.bitmap.UniversalImageUtil;
import com.inet.app.framework.device.DeviceUtil;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class FunAdapter extends ArrayAdapter<FunModel> {

	List<FunModel> mFunModels;
	Activity mContext;
	LayoutInflater mInflater;
	int widthDevice;

	public FunAdapter(Activity context, int textViewResourceId,
			List<FunModel> models) {

		super(context, R.layout.item_listview_fun);
		this.mContext = context;
		this.mInflater = this.mContext.getLayoutInflater();
		this.mFunModels = models;
		this.widthDevice = DeviceUtil.getSimpleDeviceInfo(mContext).getWidth();
	}

	@Override
	public int getCount() {
		return mFunModels.size();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder = null;
		final FunModel model = mFunModels.get(position);

		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.item_listview_fun, null);
			holder = new ViewHolder();
			holder.mTitle = (TextView) convertView
					.findViewById(R.id.title_text);
			holder.mImage = (ImageView) convertView
					.findViewById(R.id.image_view);
			holder.mViewText = (TextView) convertView
					.findViewById(R.id.num_view_text);
			holder.mCommentText = (TextView) convertView
					.findViewById(R.id.num_comment_text);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		holder.mTitle.setText(model.getTitle());
		holder.mViewText.setText(String.valueOf(model.getViewNo()));
		UniversalImageUtil.getInstance(mContext).displayImage(model.getImg(),
				holder.mImage, new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						int width = loadedImage.getWidth();
						int height = loadedImage.getHeight();
						int heightScale = (int) ((widthDevice * 1.0f / width) * height);
						// scale image to fit screen and below limit size
						// (2048x2048)
						loadedImage = BitmapUtil.limitSizeBitmap(loadedImage,
								widthDevice, heightScale);
						if (loadedImage == null) {
							view.setVisibility(View.GONE);
							return;
						}
						((ImageView) view).setImageBitmap(loadedImage);
					}
				});

		return convertView;
	}

	static class ViewHolder {
		public TextView mTitle;
		public TextView mViewText;
		public TextView mCommentText;
		public ImageView mImage;
	}
}
